// 2013-7-28下午12:41:22  net.betou.trade.admin.action.IntermediateProviderAdministratorsAct.java

package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.page.Pagination;
import net.betou.common.util.DataConvertUtils;
import net.betou.common.util.TradeUtils;
import net.betou.common.web.RequestUtils;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.AgentAndAdminsExt;
import net.betou.trade.main.manager.agencyorproxy.AdminMng;
import net.betou.trade.main.manager.role.AgencyRoleMng;
import net.betou.trade.web.Messages;
import net.betou.trade.web.ResponseUtil;
import net.betou.trade.web.WebErrors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 居间商管理员
 * @author 叶装装
 */
@Controller
public class AgentAdminAct extends ActionSupport< AgentAndAdmins >{
	private static final Logger log = LoggerFactory.getLogger( AgentAdminAct.class );
	private static final String DIRECTORY = "admin/agent";
	
	@RequestMapping( "/agentadmin/v_list.jspx" )
	public String list( Integer pageSize, Integer pageNo, String filterStatus, String searchProperty, String searchValue, String orderProperty, String orderDirection, HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		
		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		Pagination pagination = mng.getPage( admin, searchProperty, searchValue, orderProperty, orderDirection, pageNo, pageSize, filterStatus );
		
		model.addAttribute( "admin", admin );
		
		paramToModel( model, pagination, null, pageSize, searchProperty, searchValue, orderProperty, orderDirection, filterStatus );
		return getListPage( );
	}
	
	@RequestMapping( "/agentadmin/v_add.jspx" )
	public String v_add( HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		// 系统管理员，不允许添加。
		if( !admin.getSystem( ) ){
			model.addAttribute( "roleList", roleMng.listBySelf( admin ) );
		}
		
		model.addAttribute( "admin", admin );
		
		return getAddPage( );
	}
	
	@RequestMapping ( "/agentadmin/v_edit.jspx" )
	public String v_edit( Integer id, HttpServletRequest request, ModelMap model ){

		WebErrors errors = validateUpdate( request, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins bean = mng.findById( id ); 
		
		model.addAttribute( "bean", bean );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		AgentAndAdmins deepZeroAgency = null;
		boolean system = admin.getSystem( );
		
		if( system ){
			if( bean.getDeep( ) == 0 ){ // 是顶级角色，所以这个就为bean
				deepZeroAgency = bean;
			}else{
				deepZeroAgency = mng.findById( DataConvertUtils.getInt( StringUtils.split( bean.getTopIntermedia( ), ",")[ 0 ] ) );
			}
			
			model.addAttribute( "roleList", roleMng.list( admin, deepZeroAgency ) );
		}else{
			model.addAttribute( "roleList", roleMng.listBySelf( admin ) );
		}
		
		model.addAttribute( "admin", admin );
		return getUpdatePage( );
	}
	
	@RequestMapping ( "/agentadmin/o_update.jspx" )
	public String o_update( Boolean disabled,  Integer id, String password,  String email, String mobile,  Integer[ ] roleIds, AgentAndAdminsExt ext, HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		WebErrors errors = validateOUpdate( id, admin );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins bean = mng.findById( id );
		
		bean = mng.update( disabled, password, email, mobile, bean, ext, roleIds );
		logMng.operating( 1, request, Messages.LOG_AGENT_ADMIN, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping( "/agentadmin/o_save.jspx" )
	public String o_save( AgentAndAdmins bean, AgentAndAdminsExt ext, Integer[ ] roleIds,  HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		
		WebErrors errors = validateSave( bean, roleIds );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		String ip = RequestUtils.getIpAddr( request );
		bean = mng.save( admin, ip, roleIds, bean, ext );
		
		logMng.operating( 0, request, Messages.LOG_AGENT_ADMIN, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		
		return "redirect:v_list.jspx";
	}
	
	
	@RequestMapping( "/agentadmin/o_delete.jspx" )
	public void o_delete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		ResponseUtil util = validateDelete( ids, admin, response, request );

		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}

		AgentAndAdmins [ ] beans = mng.deleteByIds( ids );

		for ( AgentAndAdmins bean : beans ){
			log.info( "delete Admin id={}", bean.getId( ) );
			logMng.operating( 2, request, Messages.LOG_AGENT_ADMIN, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		}

		util.addSuccessResponse( Messages.getDeleteSuccessMessage( beans.length ) );

		util.renderJson( );
		return;
		
	}
	
	private ResponseUtil validateDelete( Integer [ ] ids, AgentAndAdmins admin, HttpServletResponse response, HttpServletRequest request ) {
		ResponseUtil util = ResponseUtil.create( response );

		if( ids == null || ids.length == 0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}

		for ( Integer id : ids ){
			AgentAndAdmins bean = mng.findAdmin( admin, id );
			
			
			if( bean == null ){
				util.addErrorResponse( admin.getSystem( ) ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING );
				break;
			}
		}
		return util;
	}
	
	
	private WebErrors validateOUpdate( Integer id, AgentAndAdmins admin ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		AgentAndAdmins bean = mng.findAdmin( admin, id ) ; 
		
		if( bean == null ){
			errors.addError( Messages.DATA_NOT_OPERATING );
			return errors;
		}
		
		return errors;
		
	}
	
	
	private WebErrors validateUpdate( HttpServletRequest request, Integer id ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		AgentAndAdmins admin = mng.findAdmin( id );
		
		if( admin == null ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		return errors;
			
	}
	
	private WebErrors validateSave( AgentAndAdmins bean, Integer [ ] roleIds ){
		WebErrors errors = WebErrors.create( );
		
		return errors;
	}
	
//	private WebErrors validateToSave( HttpServletRequest request, AgentAndAdmins user ){
//		
//		WebErrors errors = WebErrors.create( );
//		
//		if( user.getSystem( ) ){
//			log.info( Messages.AGENT_ADMIN_SYSTEM_MANAGER_NOT_TO_ADD );
//			errors.addError( Messages.AGENT_ADMIN_SYSTEM_MANAGER_NOT_TO_ADD );
//			return errors;
//		}
//		
//		return errors;
//		
//	}
	
	@Override
	protected String getDirectory( ) {
		
		return DIRECTORY;
	}
	
	@Autowired
	private AdminMng mng;
	
	@Autowired
	private AgencyRoleMng roleMng;

}
